<template>
	<view class="tour-detail flat-page">
		<!-- 主内容区 -->
		<scroll-view class="main-content" scroll-y>
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text>加载中...</text>
			</view>
			<!-- 顶部卡片模块 -->
			<view v-if="!loading" class="group-top-card" :class="{ 'section-enter': sectionEnter }">
				<!-- 基本信息和倒计时 -->
				<view class="group-card-content">
					<!-- 左侧信息区 -->
					<view class="group-info-left">
						<view class="group-name-section">
							<text class="group-name">{{ this.group.groupName || '暂无团名' }}</text>
							<text class="group-code">团号: {{ this.group.groupCode || '暂无' }}</text>
						</view>
						<view class="group-status-section">
							<text
								class="status-badge status-recruiting">{{ this.getStatusText(this.group.status) }}</text>
							<image v-if="this.isshow" class="status-edit-icon" src="/static/icons/replace.png"
								mode="aspectFit" @click="openStatusEditDrawer" />
							<text class="remaining-quota">人数
								{{ this.group.groupSize || 0 }}/{{ this.group.capacity || 0 }} </text>

						</view>
					</view>
					<!-- 右侧倒计时区 -->
					<view class="countdown-section">
						<!-- 倒计时信息 -->
						<view class="countdown-info">
							<text class="countdown-label">出发倒计时</text>
							<text class="countdown-days">{{ this.countdownDays }}天</text>
						</view>

						<!-- 导游信息 - 放在倒计时下方 -->
						<view class="guide-info">
							<text class="guide-label">导游：</text>
							<text class="guide-value">{{ group.guideName || '未分配' }}</text>
							<text v-if="this.isshow" class="icon-edit" @click="openGuideSelection">✏️</text>
							<text v-if="group.guideName && this.isshow" class="icon-unbind"
								@click.stop="showUnbindGuideConfirm">❌</text>
						</view>
					</view>
				</view>

				<!-- 基础信息区域 -->
				<view class="basic-info">
					<!-- 日期 -->
					<view class="info-row">
						<text class="info-label">日期：</text>
						<text
							class="info-value">{{ this.formatDateRange(this.group.startDate, this.group.endDate) }}</text>
					</view>
					<!-- 行程 -->
					<view class="info-row">
						<text class="info-label">行程：</text>
						<text class="info-value">{{ this.group.itineraryName || '暂无' }}</text>
					</view>
					<!-- 车辆 -->
					<view class="info-row">
						<text class="info-label">车辆：</text>
						<text class="info-value">
							{{ this.group.driverName || '未分配' }}-{{ `${this.group.vehicleLicensePlate || '未分配'}${this.group.vehicleType ? `（${this.group.vehicleType}）` : ''}` }}</text>
						<text v-if="this.isshow" class="icon-edit" @click="this.showVehicleDrawer = true">✏️</text>
						<text v-if="group.vehicleLicensePlate && this.isshow" class="icon-unbind"
							@click.stop="showUnbindVehicleConfirm">❌</text>
					</view>
					<!-- 取消团按钮 -->
					<view class="info-row cancel-group-row">
						<view class="cancel-group-container">
							<button v-if="this.isshow" class="cancel-group-btn"
								@click="showCancelGroupConfirm">取消团</button>
						</view>
					</view>
				</view>
			</view>
			<!-- 原基础信息区域已移至顶部卡片模块 -->

			<!-- 3. 团订单列表（可折叠） -->
			<view v-if="!loading" class="order-list flat-section" :class="{ 'section-enter': sectionEnter }">
				<view class="section-header" @click="toggleOrderCollapse">
					<text class="section-title flat-title">订单列表</text>
					<view class="section-actions">
						<image class="action-icon" src="/static/icons/help.png" mode="aspectFit"
							@click.stop="showOrderHelpModal = true"></image>

						<view v-if="this.isshow" class="add-btn" @click.stop="navigateToAddOrder">
							<text class="add-text">添加订单 ➕ </text>
						</view>
					</view>
				</view>

				<!-- 折叠内容区域 -->
				<view class="collapse-content" v-if="!orderCollapsed">
					<!-- 空状态 -->
					<view class="empty-state" v-if="group.orders.length === 0">
						<text class="empty-text">暂无订单数据</text>
					</view>

					<!-- 订单项 -->
					<view class="order-item flat-list-item" v-for="(order, idx) in group.orders" :key="order.id"
						:class="{ 'item-hover': isHoveringOrder === idx }" @touchstart="isHoveringOrder = idx"
						@touchend="isHoveringOrder = -1">
						<view class="order-header">
							<text class="order-no">订单号：{{ order.orderNo }}</text>
							<view class="order-status-container">
								<text class="order-status"
									:class="getOrderStatusClass(order.status)">{{ order.status }}</text>
								<view class="inline-actions">
									<image v-if="this.isshow" class="action-icon" src="/static/icons/team-fill.png"
										mode="aspectFit" @click.stop="viewGuestsByOrder(order.id)"></image>
									<image v-if="this.isshow" class="action-icon" src="/static/icons/add-friend.png"
										mode="aspectFit" @click.stop="navigateToAddGuestByOrder(order)"></image>
									<image v-if="this.isshow" class="action-icon" src="/static/icons/update.png"
										mode="aspectFit" @click.stop="navigateToEditOrder(order)"></image>
									<image v-if="this.isshow" class="action-icon" src="/static/icons/del.png"
										mode="aspectFit" @click.stop="handleDeleteOrder(idx)"></image>
								</view>
							</view>
						</view>
						<view class="order-body">
							<text class="order-info">金额：{{ order.amount }}元</text>
							<text class="order-info">下单时间：{{ order.createTime }}</text>
							<text class="order-info" v-if="order.contactPhone"
								@click.stop="makePhoneCall(order.contactPhone)">☎ 联系电话：{{ order.contactPhone }}</text>
						</view>

						<!-- 底部标签区域 -->
						<view class="order-tags">
							<view v-if="order.numberPeople > 0" class="tag-item tag-adult">
								<text class="tag-icon">👤</text>
								<text>人数 x{{ order.numberPeople }}</text>
							</view>
							<!-- <view v-if="order.childCount > 0" class="tag-item tag-child">
								<text class="tag-icon">👶</text>
								<text>儿童 x{{ order.childCount }}</text>
							</view>
							<view v-if="order.seniorCount > 0" class="tag-item tag-senior">
								<text class="tag-icon">👴</text>
								<text>老人 x{{ order.seniorCount }}</text>
							</view> -->
						</view>

					</view>
				</view>
			</view>

			<!-- 4. 客人列表（可折叠，与订单关联） -->
			<view v-if="!loading" class="guest-list flat-section guest-card-section"
				:class="{ 'section-enter': sectionEnter }">
				<view class="section-header" @click="toggleGuestCollapse">
					<view class="title-with-icon">
						<image src="/static/icons/team-fill.png" class="title-icon" mode="aspectFit" />
						<text class="section-title flat-title">客人信息</text>
					</view>

				</view>

				<!-- 返回所有订单按钮（仅在查看特定订单出行人时显示） -->
				<view class="back-to-all" v-if="currentOrderId">
					<button class="back-btn" @click="backToAllGuests">
						返回查看所有出行人
					</button>
				</view>

				<!-- 折叠内容区域 -->
				<view class="collapse-content" v-if="!guestCollapsed">
					<!-- 空状态 -->
					<view class="empty-state" v-if="filteredGuests.length === 0">
						<text class="empty-text">暂无出行人数据</text>
					</view>

					<!-- 客人列表 - 双列网格布局 -->
					<view class="guest-grid">
						<!-- 客人项 -->
						<view class="guest-card" v-for="(guest, idx) in filteredGuests" :key="guest.id">
							<!-- 客人卡片内容 -->
							<view class="guest-content">
								<!-- 圆形头像，根据姓氏生成不同背景色 -->
								<view class="guest-avatar" :class="getAvatarClass(guest.name)">
									<text class="avatar-text">{{ getAvatarText(guest.name) }}</text>
								</view>

								<!-- 中间信息区域 -->
								<view class="guest-info">
									<text class="guest-name">{{ guest.name }}</text>
									<text class="guest-phone" v-if="guest.phone"
										@click.stop="makePhoneCall(guest.phone)">{{ guest.phone }}</text>
								</view>

								<!-- 右侧操作按钮 -->
								<view class="guest-actions">
									<image v-if="this.isshow" class="action-icon edit-icon"
										src="/static/icons/update.png" mode="aspectFit"
										@click.stop="navigateToEditGuest(idx)"></image>
									<image v-if="this.isshow" class="action-icon delete-icon"
										src="/static/icons/del.png" mode="aspectFit"
										@click.stop="handleDeleteGuest(idx)"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部留白 -->
			<view class="bottom-space"></view>
		</scroll-view>

		<!-- 5. 修改团状态 - 底部抽屉 -->
		<view class="drawer status-drawer flat-drawer" :class="{ show: showStatusDialog }">
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">修改团状态</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="showStatusDialog = false" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view class="drawer-item flat-drawer-item" v-for="(text, value) in statusMap" :key="value"
					:class="{ active: selectedStatus === value }" @click="selectGroupStatus(value)">
					<text class="item-text">{{ text }}</text>
					<image src="/static/icons/check.png" class="item-check" mode="aspectFit"
						v-if="selectedStatus === value" />
				</view>
			</view>
			<view class="drawer-footer flat-drawer-footer">
				<button class="drawer-btn confirm-btn" @click="confirmStatusChange">确定</button>
			</view>
		</view>

		<!-- 6. 修改订单状态 - 底部抽屉 -->
		<view class="drawer order-status-drawer flat-drawer" :class="{ show: showOrderStatusDialog }">
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">修改订单状态</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="showOrderStatusDialog = false" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view class="drawer-item flat-drawer-item" v-for="status in orderStatusOptions" :key="status"
					:class="{ active: selectedOrderStatus === status }" @click="selectOrderStatus(status)">
					<text class="item-text">{{ status }}</text>
					<image src="/static/icons/check.png" class="item-check" mode="aspectFit"
						v-if="selectedOrderStatus === status" />
				</view>
			</view>
			<view class="drawer-footer flat-drawer-footer">
				<button class="drawer-btn confirm-btn" @click="confirmOrderStatusChange">确定</button>
			</view>
		</view>

		<!-- 导游选择抽屉 -->
		<view class="drawer guide-drawer flat-drawer" :class="{ show: showGuideDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择导游</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit" @click="closeGuideDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="guideSearchText" placeholder="搜索导游名称" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="filteredGuides.length > 0">
					<view v-for="(guide, idx) in filteredGuides" :key="idx" class="drawer-item flat-drawer-item"
						:class="{ active: group.guideId === filteredGuideIds[idx] }" @click="selectGuide(idx, true)">
						<text class="item-name">{{ guide }}</text>
						<image v-if="group.guideId === filteredGuideIds[idx]" src="/static/icons/check.png"
							class="item-selected" mode="aspectFit" />
					</view>
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的导游</text>
				</view>
			</view>
		</view>

		<!-- 车辆选择抽屉 -->
		<view class="drawer vehicle-drawer flat-drawer" :class="{ show: showVehicleDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择车辆</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="closeVehicleDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="vehicleSearchText" placeholder="搜索车辆信息" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="filteredVehicles.length > 0" v-for="(vehicle, idx) in filteredVehicles" :key="idx"
					class="drawer-item flat-drawer-item vehicle-item"
					:class="{ active: group.vehicleId === filteredVehicleIds[idx] }" @click="selectVehicle(idx, true)">
					<!-- 车辆信息容器 -->
					<view class="vehicle-content">
						<!-- 车辆主信息 - 一行展示 -->
						<view class="vehicle-main-info">
							<text class="vehicle-title">{{ vehicle }}</text>
						</view>
						<!-- 车辆详细信息（如果有） -->
						<view v-if="filteredVehicleDetails[idx] && filteredVehicleDetails[idx].licensePlate"
							class="vehicle-info-details">
							<text class="vehicle-detail-item">
								<text class="detail-label">车牌号:</text>
								<text
									class="detail-value">{{ filteredVehicleDetails[idx].licensePlate || '未提供' }}</text>
							</text>
							<text class="vehicle-detail-item">
								<text class="detail-label">司机:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].driverName || '未指定' }}</text>
							</text>
							<text class="vehicle-detail-item">
								<text class="detail-label">电话:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].driverPhone || '未提供' }}</text>
							</text>
							<!-- 显示载客量信息 -->
							<text v-if="filteredVehicleDetails[idx].loadCapacity" class="vehicle-detail-item">
								<text class="detail-label">载客量:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].loadCapacity }}人</text>
							</text>
						</view>
					</view>
					<!-- 选中标记 -->
					<image v-if="group.vehicleId === filteredVehicleIds[idx]" src="/static/icons/check.png"
						class="item-selected" mode="aspectFit" />
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的车辆</text>
				</view>
			</view>
		</view>

		<!-- 全局抽屉遮罩层 -->
		<view class="drawer-mask flat-mask"
			:class="{ show: showGuideDrawer || showVehicleDrawer || showStatusDialog || showOrderStatusDialog }"
			@click="closeAllDrawers">
		</view>

	</view>

	<!-- 订单操作说明弹窗 -->
	<view class="help-modal" v-if="showOrderHelpModal">
		<view class="help-modal-overlay" @click="showOrderHelpModal = false"></view>
		<view class="help-modal-content">
			<view class="help-modal-header">
				<text class="help-modal-title">订单操作说明</text>
			</view>
			<view class="help-modal-body">
				<view class="help-item">
					<view class="help-icon blue-bg">
						<image src="/static/icons/team-fill.png" mode="aspectFit"></image>
					</view>
					<view class="help-text">
						<text class="help-title">查看客人</text>
						<text class="help-desc">查看当前订单下的所有客人信息</text>
					</view>
				</view>
				<view class="help-item">
					<view class="help-icon blue-bg">
						<image src="/static/icons/add-friend.png" mode="aspectFit"></image>
					</view>
					<view class="help-text">
						<text class="help-title">添加客人</text>
						<text class="help-desc">为当前订单添加新的客人信息</text>
					</view>
				</view>
				<view class="help-item">
					<view class="help-icon red-bg">
						<image src="/static/icons/del.png" mode="aspectFit"></image>
					</view>
					<view class="help-text">
						<text class="help-title">删除订单</text>
						<text class="help-desc">删除当前订单，此操作不可撤销</text>
					</view>
				</view>
			</view>
			<view class="help-modal-footer">
				<button class="help-confirm-btn" @click="showOrderHelpModal = false">我知道了</button>
			</view>
		</view>
	</view>

	<!-- 客人添加方式选择弹窗 -->
	<view class="help-modal" v-if="showAddGuestModal">
		<view class="help-modal-overlay" @click="showAddGuestModal = false"></view>
		<view class="help-modal-content">
			<view class="help-modal-header">
				<text class="help-modal-title">选择添加方式</text>
			</view>
			<view class="help-modal-body">
				<view class="help-item" @click="selectAddGuestMethod('basic')">
					<view class="help-icon blue-bg">
						<image src="/static/icons/add-friend.png" mode="aspectFit"></image>
					</view>
					<view class="help-text">
						<text class="help-title">基础添加</text>
						<text class="help-desc">手动输入客人信息</text>
					</view>
				</view>
				<view class="help-item" @click="selectAddGuestMethod('smart')">
					<view class="help-icon orange-bg">
						<image src="/static/icons/replace.png" mode="aspectFit"></image>
					</view>
					<view class="help-text">
						<text class="help-title">智能解析</text>
						<text class="help-desc">批量解析客人信息</text>
					</view>
				</view>
			</view>
			<view class="help-modal-footer">
				<button class="help-confirm-btn" @click="showAddGuestModal = false">取消</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getTourGroupDetail,
		bindGuideToTourGroup,
		bindVehicleToTourGroup,
		unbindGuideFromTourGroup,
		updateTourGroupStatus,
		deleteTourGroupById
	} from '@/https/tourgroup.js';
	import {
		getOrderList,
		getOrderStatusText,
		deleteOrderById
	} from '@/https/order.js';
	import {
		getTravelerList,
		deleteTraveler
	} from '@/https/traveler.js';
	import {
		GetSelectList as getGuideSelectList
	} from '@/https/guide.js';
	import {
		GetSelectList as getVehicleSelectList,
		unbindVehicleFromTourGroup
	} from '@/https/vehicle.js';
	export default {
		data() {
			return {
				// 1. 接收团ID与初始化团数据
				groupId: '',
				group: {
					id: 0,
					groupName: '',
					groupCode: '',
					startDate: '',
					endDate: '',
					status: 0,
					itineraryName: '',
					guideName: '',
					vehicleLicensePlate: '',
					vehicleType: '',
					driverName: '',
					capacity: 0, // 总容量
					remainingQuota: 0, // 剩余名额
					orders: [], // 订单列表，每个订单包含id用于关联客人
					guests: [] // 客人列表，每个客人包含orderId关联所属订单
				},
				loading: false,
				// 加载导游和车辆状态
				loadingGuidesAndVehicles: false,
				isshow: true,
				// 2. 折叠状态管理
				orderCollapsed: false, // 订单列表是否折叠
				guestCollapsed: false, // 客人列表是否折叠
				// 订单帮助弹窗
				showOrderHelpModal: false,

				// 3. 订单-客人关联管理
				currentOrderId: '', // 当前查看的订单ID（用于筛选客人）
				currentOrderName: '', // 当前查看的订单号

				// 4. 页面交互状态
				sectionEnter: false,
				isHoveringOrder: -1,
				isHoveringGuest: -1,

				// 5. 抽屉控制状态
				showOrderStatusDialog: false,
				showStatusDialog: false,
				selectedStatus: 0,

				// 6. 状态选择数据
				statusMap: {
					0: '招募中',
					1: '已成团',
					2: '已出发',
					3: '已结束',
					4: '已取消'
				},
				// 性别映射：0-男，1-女，2-未知
				genderMap: {
					0: '男',
					1: '女',
					2: '未知'
				},
				// 添加客人方式选择弹窗
				showAddGuestModal: false,
				currentOrder: null,
				orderStatusOptions: ['待支付', '已支付', '已取消', '已完成', '已退款'],
				selectedOrderStatus: '',
				editingOrderIndex: -1,

				// 7. 删除确认相关（使用微信小程序原生模态框）
				confirmMessage: '',
				deleteType: '',
				deleteIndex: -1,

				// 导游选择相关
				showGuideDrawer: false,
				guides: [],
				guideIds: [],
				guideSearchText: '',
				submitting: false,
				// 解绑导游确认弹窗
				showUnbindGuideDialog: false,
				// 解绑车辆确认弹窗
				showUnbindVehicleDialog: false,
				// 取消团确认弹窗
				showCancelGroupDialog: false,

				// 车辆选择相关
				showVehicleDrawer: false,
				vehicles: [],
				vehicleIds: [],
				vehicleDetails: [],
				vehicleSearchText: ''
			};
		},
		onLoad(options) {
			// // 获取页面参数
			this.groupId = options.groupId || '';

			// // 加载团详情数据
			// this.loadGroupDetail();

			// // 触发动画
			// this.$nextTick(() => {
			// 	this.sectionEnter = true;
			// });
		},
		onShow() {
			// 在onShow中通过this.$mp.query获取页面参数
			const query = this.$mp && this.$mp.query ? this.$mp.query : {};
			// 如果有新的groupId，则更新
			if (query.groupId) {
				this.groupId = query.groupId;
			}

			// 加载团详情数据
			this.loadGroupDetail();
			// 加载导游和车辆列表
			this.loadGuidesAndVehicles();

			// 触发动画
			this.$nextTick(() => {
				this.sectionEnter = true;
			});
		},
		computed: {
			// 计算出发倒计时天数
			countdownDays() {
				if (!this.group.startDate) return 0;

				// 标准化日期字符串以兼容iOS
				const normalizeDateStr = (dateStr) => {
					if (!dateStr) return dateStr;
					// 将空格分隔符替换为T
					let normalized = dateStr.replace(/\s+/g, 'T');
					// 如果是yyyy-MM-dd格式，尝试转换为yyyy/MM/dd格式
					if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
						normalized = normalized.replace(/-/g, '/');
					}
					return normalized;
				};

				const now = new Date();
				let startDate;

				// 尝试解析日期，如果失败则尝试标准化后再次解析
				try {
					startDate = new Date(this.group.startDate);
					// 检查日期是否有效
					if (isNaN(startDate.getTime())) {
						// 尝试标准化后再次解析
						const normalizedDate = normalizeDateStr(this.group.startDate);
						startDate = new Date(normalizedDate);
						// 如果仍然无效，记录错误并返回0
						if (isNaN(startDate.getTime())) {
							console.error('无法解析的日期格式:', this.group.startDate);
							return 0;
						}
					}
				} catch (error) {
					console.error('日期解析错误:', error);
					return 0;
				}

				// 设置时间为当天的0点0分0秒，避免时间部分的影响
				now.setHours(0, 0, 0, 0);
				startDate.setHours(0, 0, 0, 0);

				// 计算天数差
				const diffTime = startDate - now;
				const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

				return Math.max(0, diffDays); // 确保不会出现负数
			},

			// 过滤显示的客人（根据当前选择的订单）
			filteredGuests() {
				console.log(this.currentOrderId)
				if (this.currentOrderId) {
					// 使用字符串类型进行匹配，确保类型一致性
					return this.group.guests.filter(guest => String(guest.orderId) === String(this.currentOrderId));
				}
				return this.group.guests;
			},

			// 过滤后的导游列表
			filteredGuides() {
				if (!this.guideSearchText) return this.guides;
				return this.guides.filter(guide =>
					guide.toLowerCase().includes(this.guideSearchText.toLowerCase())
				);
			},

			// 过滤后的导游ID列表
			filteredGuideIds() {
				if (!this.guideSearchText) return this.guideIds;
				const searchText = this.guideSearchText.toLowerCase();
				return this.guides
					.map((guide, index) => ({
						guide,
						index
					}))
					.filter(item => item.guide.toLowerCase().includes(searchText))
					.map(item => this.guideIds[item.index]);
			},

			// 过滤后的车辆列表
			filteredVehicles() {
				if (!this.vehicleSearchText) return this.vehicles;
				return this.vehicles.filter(vehicle =>
					vehicle.toLowerCase().includes(this.vehicleSearchText.toLowerCase())
				);
			},

			// 过滤后的车辆ID列表
			filteredVehicleIds() {
				if (!this.vehicleSearchText) return this.vehicleIds;
				const searchText = this.vehicleSearchText.toLowerCase();
				return this.vehicles
					.map((vehicle, index) => ({
						vehicle,
						index
					}))
					.filter(item => item.vehicle.toLowerCase().includes(searchText))
					.map(item => this.vehicleIds[item.index]);
			},

			// 过滤后的车辆详情列表
			filteredVehicleDetails() {
				if (!this.vehicleSearchText) return this.vehicleDetails;
				const searchText = this.vehicleSearchText.toLowerCase();
				return this.vehicles
					.map((vehicle, index) => ({
						vehicle,
						index
					}))
					.filter(item => item.vehicle.toLowerCase().includes(searchText))
					.map(item => this.vehicleDetails[item.index]);
			},

			// 基础信息列表已移至模板直接实现，不再使用计算属性
		},
		methods: {
			// 加载导游和车辆列表
			async loadGuidesAndVehicles() {
				console.log('开始加载导游和车辆列表');
				if (!this.groupId) {
					console.warn('缺少团ID参数');
					return;
				}

				// 显示加载状态
				this.loadingGuidesAndVehicles = true;

				try {
					// 构建导游参数 - 与addgroup.vue保持一致的格式
					const guideParams = {
						StartDate: this.group.startDate || '',
						EndDate: this.group.endDate || ''
					};
					console.log('导游参数:', guideParams);

					// 构建车辆参数，团人数使用group.capacity
					const vehicleParams = {
						StartDate: this.group.startDate || '',
						EndDate: this.group.endDate || '',
						count: this.group.capacity || 0 // 使用团人数
					};

					// 并发请求导游和车辆列表
					const [guideList, vehicleList] = await Promise.all([
						getGuideSelectList(guideParams),
						getVehicleSelectList(vehicleParams)
					]);

					// 处理导游数据 - 参照addgroup.vue的处理方式
					console.log('获取到的导游列表:', guideList);
					if (Array.isArray(guideList) && guideList.length > 0) {
						this.guides = guideList.map(item => item.Label || '未知导游');
						this.guideIds = guideList.map(item => item.Value || null);
						console.log('处理后的导游列表:', this.guides);
						console.log('处理后的导游ID列表:', this.guideIds);
					} else {
						console.warn('导游列表为空或格式不正确');
						this.guides = ['暂无可用导游'];
						this.guideIds = [null];
						console.log('使用默认导游列表:', this.guides);
					}

					// 处理车辆数据 - 参照addgroup.vue的处理方式
					if (Array.isArray(vehicleList) && vehicleList.length > 0) {
						console.log('获取到的车辆列表:', vehicleList);
						// 存储完整的车辆详情
						this.vehicleDetails = vehicleList;
						// 格式化显示的车辆文本
						this.vehicles = vehicleList.map(item => {
							if (item.Label) {
								return item.Label;
							} else if (item.licensePlate) {
								return `${item.licensePlate} - ${item.vehicleType || '未知车型'} - 核载${item.loadCapacity || 0}人`;
							}
							return '未知车辆';
						});
						// 提取车辆ID，优先使用vehicleId字段
						this.vehicleIds = vehicleList.map(item => {
							const vehicleId = item.vehicleId || item.Value;
							console.log('车辆ID处理:', {
								原始ID: item.Value,
								vehicleId: item.vehicleId,
								最终使用: vehicleId
							});
							return vehicleId || null;
						});
					} else {
						console.warn('车辆列表为空或格式不正确');
						this.vehicles = ['暂无可用车辆'];
						this.vehicleIds = [null];
						this.vehicleDetails = [];
					}

				} catch (error) {
					console.error('加载导游和车辆失败:', error);
					uni.showToast({
						title: '加载导游和车辆列表失败，请重试',
						icon: 'none'
					});
					// 重置数据，避免显示错误信息
					this.guides = ['加载失败，请重试'];
					this.guideIds = [null];
					this.vehicles = ['加载失败，请重试'];
					this.vehicleIds = [null];
					this.vehicleDetails = [];
				} finally {
					// 隐藏加载状态
					this.loadingGuidesAndVehicles = false;
				}
			},

			// 加载团详情数据
			async loadGroupDetail() {
				if (!this.groupId) {
					uni.showToast({
						title: '团ID不能为空',
						icon: 'none'
					});
					return;
				}

				this.loading = true;
				try {

					// 调用API获取团详情
					const params = {
						id: parseInt(this.groupId)
					};

					const res = await getTourGroupDetail(params);

					if (res) {
						this.isshow = res.status == 4 ? false : true;
						// 赋值基本信息
						Object.assign(this.group, res);

						// 加载订单数据
						await this.loadOrders();

						// 加载导游和车辆列表
						this.loadGuidesAndVehicles();
					} else {
						uni.showToast({
							title: '获取数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载团详情失败:', error);
					uni.showToast({
						title: '网络异常，请重试',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 加载订单数据
			async loadOrders() {
				try {

					const orderParams = {
						tourGroupId: parseInt(this.groupId)
					};

					// 获取订单列表
					const orderData = await getOrderList(orderParams);
					// 转换订单状态为文本
					if (Array.isArray(orderData)) {
						this.group.orders = orderData.map(order => ({
							...order,
							status: getOrderStatusText(order.status),
							createTime: this.formatDate(order.create_time || new Date().toISOString())
						}));
					} else {
						this.group.orders = [];
					}

					// 根据团ID获取所有游客信息
					const travelerParams = {
						tourGroupId: parseInt(this.groupId)
					};
					const travelerData = await getTravelerList(travelerParams);

					// 处理游客数据，确保包含所需字段
					if (Array.isArray(travelerData)) {
						this.group.guests = travelerData.map(guest => ({
							id: guest.id,
							name: guest.name || '',
							gender: guest.gender || 0,
							idCard: guest.idCard || '',
							phone: guest.phone || '',
							roomNo: guest.roomNo || 0,
							orderId: guest.orderId, // 保留原始类型，在过滤时进行类型转换
							// 添加新数据格式字段
							address: guest.address || '',
							birthday: guest.birthday || '0001-01-01 00:00:00',
							emergencyContact: guest.emergencyContact || '',
							emergencyPhone: guest.emergencyPhone || '',
							orderNo: guest.orderNo || '',
							update_time: guest.update_time || '0001-01-01 00:00:00'
						}));
						console.log('游客数据加载完成:', this.group.guests);
					} else {
						this.group.guests = [];
					}
				} catch (error) {
					console.error('加载订单和游客数据失败:', error);
					this.group.orders = [];
					this.group.guests = [];
				}
			},

			// 格式化日期 - 增强的iOS兼容版本
			formatDate(dateStr) {
				// 扩展空日期检查范围
				if (!dateStr || dateStr === '0001-01-01T00:00:00' || dateStr === '0001-01-01 00:00:00') return '--';
				try {
					// 确保日期字符串是iOS兼容格式
					// 替换点为横杠，并处理空格分隔的情况（替换为T）
					const normalizedDateStr = dateStr.replace(/\./g, '-').replace(/\s+/g, 'T');
					let date = new Date(normalizedDateStr);

					// 检查日期是否有效，如果无效尝试转换格式（yyyy-MM-dd -> yyyy/MM/dd）
					if (isNaN(date.getTime())) {
						// 尝试将yyyy-MM-dd格式转换为yyyy/MM/dd格式
						const altFormat = normalizedDateStr.replace(/-/g, '/');
						date = new Date(altFormat);

						// 如果仍然无效，记录错误并返回
						if (isNaN(date.getTime())) {
							console.error('日期解析失败:', dateStr, '尝试过的格式:', normalizedDateStr, altFormat);
							return '--';
						}
					}

					return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
				} catch (e) {
					console.error('日期格式化错误:', e, '日期字符串:', dateStr);
					return '--';
				}
			},

			// 打开状态编辑抽屉
			openStatusEditDrawer() {
				this.selectedStatus = this.group.status;
				this.showStatusDialog = true;
			},

			// 选择团状态
			selectGroupStatus(status) {
				this.selectedStatus = status;
			},

			// 确认修改团状态
			async confirmStatusChange() {
				if (this.selectedStatus === this.group.status) {
					uni.showToast({
						title: '未修改状态',
						icon: 'none'
					});
					this.showStatusDialog = false;
					return;
				}

				try {
					const openId = wx.getStorageSync('openId');
					const params = {
						id: this.group.id,
						status: this.selectedStatus,
						openId: openId
					};

					const res = await updateTourGroupStatus(params);

					if (res && res.code === 200) {
						uni.showToast({
							title: '状态更新成功',
							icon: 'success'
						});
						// 更新本地状态
						this.group.status = this.selectedStatus;
						// 重新加载团详情
						await this.loadGroupDetail();
					} else {
						uni.showToast({
							title: res?.message || '状态更新失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('更新团状态失败:', error);
					uni.showToast({
						title: '状态更新失败，请重试',
						icon: 'none'
					});
				} finally {
					this.showStatusDialog = false;
				}
			},

			// 工具函数：状态处理
			// 复用getStatusText方法，已移到上方

			getStatusClass(status) {
				const map = {
					0: 'status-recruiting flat-status',
					1: 'status-formed flat-status',
					2: 'status-started flat-status',
					3: 'status-completed flat-status',
					4: 'status-canceled flat-status'
				};
				return map[status] || '';
			},

			// 获取状态文本
			getStatusText(status) {
				switch (status) {
					case 0:
						return '招募中';
					case 1:
						return '已成团';
					case 2:
						return '已出发';
					case 3:
						return '已结束';
					case 4:
						return '已结束';
					case 5:
						return '已取消';
					default:
						return '招募中';
				}
			},

			// 格式化日期范围 - 增强的iOS兼容版本，包含换行
			formatDateRange(startDate, endDate) {
				const formatDate = (dateStr) => {
					if (!dateStr || dateStr === '0001-01-01T00:00:00' || dateStr === '0001-01-01 00:00:00')
						return '--';
					try {
						// 标准化日期字符串以兼容iOS
						let normalizedDateStr = dateStr;
						// 替换常见的分隔符问题
						normalizedDateStr = normalizedDateStr.replace(/\./g, '-');
						// 将空格分隔符替换为T（iOS要求的格式）
						normalizedDateStr = normalizedDateStr.replace(/\s+/g, 'T');

						let date = new Date(normalizedDateStr);

						// 检查日期是否有效，如果无效则尝试转换格式
						if (isNaN(date.getTime())) {
							// 尝试将yyyy-MM-dd格式转换为yyyy/MM/dd格式（iOS更可靠支持）
							if (/^\d{4}-\d{2}-\d{2}$/.test(normalizedDateStr)) {
								normalizedDateStr = normalizedDateStr.replace(/-/g, '/');
								date = new Date(normalizedDateStr);
							}

							// 如果仍然无效，返回占位符
							if (isNaN(date.getTime())) {
								console.error('无法解析的日期格式:', dateStr);
								return '--';
							}
						}

						return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
					} catch (e) {
						console.error('日期范围格式化错误:', e);
						return '--';
					}
				};

				const start = formatDate(startDate);
				const end = formatDate(endDate);

				// 使用\n实现换行显示
				return `${start} 至 ${end}`;
			},

			getOrderStatusClass(status) {
				return status === '已支付' || status === '已完成' ? 'order-paid' :
					status === '已取消' || status === '已退款' ? 'order-canceled' : 'order-unpaid';
			},

			// 工具函数：订单-客人关联
			// 根据订单ID获取该订单下的客人数量
			getGuestCountByOrder(orderId) {
				return this.group.guests.filter(guest => guest.orderId === orderId).length;
			},

			// 根据订单ID获取订单号
			getOrderNoById(orderId) {
				const order = this.group.orders.find(o => o.id === orderId);
				return order ? order.orderNo : '未知订单';
			},

			// 折叠控制
			toggleOrderCollapse() {
				this.orderCollapsed = !this.orderCollapsed;
			},

			toggleGuestCollapse() {
				this.guestCollapsed = !this.guestCollapsed;
			},

			// 订单-客人关联操作
			// 查看特定订单的客人
			viewGuestsByOrder(orderId) {
				// 确保使用字符串类型进行匹配，避免类型不匹配问题
				this.currentOrderId = String(orderId);
				// 获取订单号
				const order = this.group.orders.find(o => String(o.id) === String(orderId));
				if (order) {
					this.currentOrderName = order.orderNo;
				}
				// 展开客人列表
				this.guestCollapsed = false;
				// 滚动到客人列表区域
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.guest-list').boundingClientRect(data => {
						if (data) {
							uni.pageScrollTo({
								scrollTop: data.top - 100, // 导航栏高度偏移
								duration: 300
							});
						}
					}).exec();
				});
			},

			// 返回查看所有客人
			backToAllGuests() {
				this.currentOrderId = '';
				this.currentOrderName = '';
			},

			selectOrderStatus(status) {
				this.selectedOrderStatus = status;
			},

			// 关闭抽屉
			closeAllDrawers() {
				this.showOrderStatusDialog = false;
				this.showGuideDrawer = false;
				this.showVehicleDrawer = false;
				this.showStatusDialog = false;
			},

			// 订单操作
			handleEditOrderStatus(index) {
				this.editingOrderIndex = index;
				this.selectedOrderStatus = this.group.orders[index].status;
				this.showOrderStatusDialog = true;
			},

			confirmOrderStatusChange() {
				if (this.editingOrderIndex !== -1) {
					this.group.orders[this.editingOrderIndex].status = this.selectedOrderStatus;
					this.showOrderStatusDialog = false;
					uni.showToast({
						title: '订单状态修改成功',
						icon: 'success',
						duration: 1500
					});
				}
			},

			// 微信小程序适配：使用wx.showModal实现删除确认
			handleDeleteOrder(index) {
				const order = this.group.orders[index];
				const orderId = order.id;
				uni.showModal({
					title: '确认删除',
					content: `确定要删除订单 ${order.orderNo} 吗？`,
					confirmColor: '#f53f3f',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用删除订单接口
								await deleteOrderById({
									id: orderId
								});
								uni.showToast({
									title: '订单删除成功，即将刷新',
									icon: 'success',
									duration: 1500
								});
								// 接口调用成功后，重新加载团详情数据
								await this.loadGroupDetail();
								// 如果正在查看该订单的客人，返回全部视图
								if (String(this.currentOrderId) === String(orderId)) {
									this.backToAllGuests();
								}
							} catch (error) {
								console.error('删除订单失败:', error);
								uni.showToast({
									title: '删除订单失败，请重试',
									icon: 'none',
									duration: 1500
								});
							}
						}
					}
				});
			},

			// 刷新订单列表
			async refreshOrders() {
				this.loading = true;
				await this.loadOrders();
				this.loading = false;
			},

			navigateToAddOrder() {
				uni.navigateTo({
					url: `/pages/addOrder/addOrder?groupId=${this.groupId}`
				});
			},

			navigateToEditOrder(obj_order) {
				const orderStr = encodeURIComponent(JSON.stringify(obj_order));
				uni.navigateTo({
					url: `/pages/addOrder/addOrder?groupId=${this.groupId}&order=${orderStr}`
				});
			},

			// 关闭导游选择抽屉
			closeGuideDrawer() {
				this.showGuideDrawer = false;
				this.guideSearchText = ''; // 清空搜索框
			},

			// 选择导游
			async selectGuide(index, isFiltered = false) {
				const guideId = isFiltered ? this.filteredGuideIds[index] : this.guideIds[index];
				const guideName = isFiltered ? this.filteredGuides[index] : this.guides[index];

				if (!guideId || !this.groupId) {
					uni.showToast({
						title: '导游ID或团ID无效',
						icon: 'none'
					});
					return;
				}

				try {
					// 显示加载中状态
					uni.showLoading({
						title: '绑定中...'
					});

					const params = {
						guideId: Number(guideId),
						tourGroupId: Number(this.groupId)
					};

					const result = await bindGuideToTourGroup(params);
					if (result) {
						// 关闭抽屉
						this.closeGuideDrawer();

						// 刷新团详情数据，确保所有信息同步更新
						await this.loadGroupDetail();

						uni.showToast({
							title: '导游绑定成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '导游绑定失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('导游绑定失败:', error);
					uni.showToast({
						title: '导游绑定失败，请重试',
						icon: 'none'
					});
				} finally {
					// 隐藏加载状态
					uni.hideLoading();
				}
			},

			// 选择车辆
			async selectVehicle(index, isFiltered = false) {
				const vehicleId = isFiltered ? this.filteredVehicleIds[index] : this.vehicleIds[index];
				const vehicleDetail = isFiltered ? this.filteredVehicleDetails[index] : this.vehicleDetails[index];
				const vehicleName = isFiltered ? this.filteredVehicles[index] : this.vehicles[index];

				if (!vehicleId || !this.groupId) {
					uni.showToast({
						title: '车辆ID或团ID无效',
						icon: 'none'
					});
					return;
				}

				try {
					// 显示加载中状态
					uni.showLoading({
						title: '绑定中...'
					});

					// 再次确认车辆ID，如果有vehicleId字段则优先使用
					const finalVehicleId = vehicleDetail?.vehicleId || vehicleId || null;

					const params = {
						vehicleId: Number(finalVehicleId),
						tourGroupId: Number(this.groupId)
					};

					const result = await bindVehicleToTourGroup(params);
					if (result) {

						// 刷新团详情数据，确保所有信息同步更新
						await this.loadGroupDetail();

						this.showVehicleDrawer = false;
						uni.showToast({
							title: '车辆绑定成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '车辆绑定失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('车辆绑定失败:', error);
					uni.showToast({
						title: '车辆绑定失败，请重试',
						icon: 'none'
					});
				} finally {
					// 隐藏加载状态
					uni.hideLoading();
				}
			},

			// 拨打电话功能
			makePhoneCall(phoneNumber) {
				if (!phoneNumber) return;

				uni.makePhoneCall({
					phoneNumber: phoneNumber,
					success: () => {
						console.log('拨打电话成功');
					},
					fail: (error) => {
						console.error('拨打电话失败:', error);
						uni.showToast({
							title: '拨打电话失败',
							icon: 'none'
						});
					}
				});
			},

			// 客人操作
			navigateToAddGuest() {
				uni.navigateTo({
					url: `/pages/editGuest/editGuest?groupId=${this.groupId}&mode=add`
				});
			},

			// 通过订单添加出行人
			navigateToAddGuestByOrder(order) {
				// 保存当前订单信息
				this.currentOrder = {
					id: order.id,
					orderNo: order.orderNo
				};
				// 显示添加方式选择弹窗
				this.showAddGuestModal = true;
			},

			navigateToEditGuest(index) {
				const guest = this.filteredGuests[index];
				if (!guest) {
					console.error('出行人信息不存在');
					uni.showToast({
						title: '出行人信息异常',
						icon: 'none'
					});
					return;
				}
				// 将完整的出行人信息序列化为JSON字符串传递
				const guestStr = encodeURIComponent(JSON.stringify(guest));
				uni.navigateTo({
					url: `/pages/editGuest/editGuest?groupId=${this.groupId}&guestId=${guest.id || ''}&order=${guestStr}`
				});
			},

			// 微信小程序适配：使用wx.showModal实现删除确认
			async handleDeleteGuest(index) {
				const guest = this.filteredGuests[index];
				const that = this; // 保存this上下文

				uni.showModal({
					title: '确认删除',
					content: `确定要删除出行人 ${guest.name} 吗？`,
					confirmColor: '#f53f3f',
					success: async function(res) {
						if (res.confirm) {
							try {
								// 调用API删除游客
								await deleteTraveler({
									id: guest.id
								});

								uni.showToast({
									title: '出行人删除成功，即将刷新',
									icon: 'success',
									duration: 1500
								});

								// 刷新团详情数据，确保所有信息同步更新
								await that.loadGroupDetail();

							} catch (error) {
								console.error('删除游客失败:', error);
								uni.showToast({
									title: '删除失败，请重试',
									icon: 'none'
								});
							}
						}
					}
				});
			},

			// 返回上一页
			handleBack() {
				uni.navigateBack({
					delta: 1
				});
			},

			// 关闭导游抽屉
			closeGuideDrawer() {
				this.showGuideDrawer = false;
				this.guideSearchText = '';
			},

			// 关闭车辆抽屉
			closeVehicleDrawer() {
				this.showVehicleDrawer = false;
				this.vehicleSearchText = '';
			},

			// 显示解绑导游确认弹窗
			showUnbindGuideConfirm() {
				const that = this;
				uni.showModal({
					title: '解绑导游',
					content: '确定要解绑当前导游吗？',
					confirmColor: '#f53f3f',
					success: (res) => {
						if (res.confirm) {
							that.unbindGuide();
						}
					}
				});
			},

			// 解绑导游
			async unbindGuide() {
				if (!this.groupId || !this.group.guideId) {
					uni.showToast({
						title: '导游未绑定',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '解绑中...'
					});

					const params = {
						guideId: Number(this.group.guideId),
						tourGroupId: Number(this.groupId)
					};

					const result = await unbindGuideFromTourGroup(params);
					if (result) {
						// 清空导游信息
						this.group.guideId = '';
						this.group.guideName = '';
						uni.showToast({
							title: '导游解绑成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '导游解绑失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('导游解绑失败:', error);
					uni.showToast({
						title: '导游解绑失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 显示解绑车辆确认弹窗
			showUnbindVehicleConfirm() {
				const that = this;
				uni.showModal({
					title: '解绑车辆',
					content: '确定要解绑当前车辆吗？',
					confirmColor: '#f53f3f',
					success: (res) => {
						if (res.confirm) {
							that.unbindVehicle();
						}
					}
				});
			},
			// 显示取消团确认弹窗
			showCancelGroupConfirm() {
				const that = this;
				uni.showModal({
					title: '取消团',
					content: '确定要取消该团吗？此操作不可撤销！',
					confirmColor: '#f53f3f',
					success: (res) => {
						if (res.confirm) {
							that.cancelTourGroup();
						}
					}
				});
			},
			// 取消团
			async cancelTourGroup() {
				if (!this.groupId || !this.group.id) {
					uni.showToast({
						title: '团ID无效',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '取消中...'
					});

					const params = {
						id: Number(this.group.id)
					};

					const result = await deleteTourGroupById(params);
					if (result) {
						uni.showToast({
							title: '取消团成功',
							icon: 'success'
						});
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: result?.message || '取消团失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('取消团失败:', error);
					uni.showToast({
						title: '取消团失败，请稍后重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 解绑车辆
			async unbindVehicle() {
				if (!this.groupId || !this.group.vehicleId) {
					uni.showToast({
						title: '车辆未绑定',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '解绑中...'
					});

					const params = {
						tourGroupId: Number(this.groupId)
					};
					const result = await unbindVehicleFromTourGroup(params);
					if (result) {
						// 清空车辆信息
						this.group.vehicleId = '';
						this.group.vehicleLicensePlate = '';
						this.group.vehicleType = '';
						this.group.driverName = '';
						uni.showToast({
							title: '车辆解绑成功',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '车辆解绑失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('车辆解绑失败:', error);
					uni.showToast({
						title: '车辆解绑失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 打开导游选择
			openGuideSelection() {
				console.log('尝试打开导游抽屉，当前filteredGuides长度:', this.filteredGuides.length);
				// 确保导游数据已加载
				if (this.filteredGuides.length <= 1 || this.filteredGuides[0] === '加载失败，请重试') {
					// 显示加载提示
					uni.showLoading({
						title: '加载导游数据...'
					});
					this.loadGuidesAndVehicles().then(() => {
						console.log('加载导游数据后，filteredGuides长度:', this.filteredGuides.length);
						uni.hideLoading();
						// 确保有数据后再打开抽屉
						if (this.filteredGuides.length > 1 && this.filteredGuides[0] !== '加载失败，请重试' && this
							.filteredGuides[0] !== '暂无可用导游') {
							this.showGuideDrawer = true;
						} else {
							uni.showToast({
								title: '暂无导游数据',
								icon: 'none'
							});
						}
					}).catch(error => {
						console.error('加载导游数据失败:', error);
						uni.hideLoading();
						uni.showToast({
							title: '加载导游数据失败',
							icon: 'none'
						});
					});
				} else {
					this.showGuideDrawer = true;
				}
			},

			// 打开状态选择抽屉
			openStatusDrawer() {
				this.showStatusDialog = true;
				this.selectedStatus = this.group.status;
			},

			// 选择团状态
			selectGroupStatus(status) {
				this.selectedStatus = status;
			},

			// 确认状态修改
			async confirmStatusChange() {
				if (this.selectedStatus === undefined) return;

				try {
					// 显示加载中状态
					uni.showLoading({
						title: '更新中...'
					});

					// 这里应该调用更新团状态的API
					// 由于没有看到具体的API调用，暂时只更新本地状态
					this.group.status = this.selectedStatus;
					this.showStatusDialog = false;

					// 刷新团详情数据
					await this.loadGroupDetail();

					uni.showToast({
						title: '状态更新成功',
						icon: 'success'
					});
				} catch (error) {
					console.error('状态更新失败:', error);
					uni.showToast({
						title: '状态更新失败，请重试',
						icon: 'none'
					});
				} finally {
					// 隐藏加载状态
					uni.hideLoading();
				}
			},

			// 关闭所有抽屉
			closeAllDrawers() {
				this.showGuideDrawer = false;
				this.showVehicleDrawer = false;
				this.showStatusDialog = false;
				this.showOrderStatusDialog = false;
				this.guideSearchText = '';
				this.vehicleSearchText = '';
			},

			selectOrderStatus(status) {
				this.selectedOrderStatus = status;
			},
			// 获取头像背景色样式类
			getAvatarClass(name) {
				const colors = ['avatar-purple', 'avatar-pink', 'avatar-yellow', 'avatar-cyan'];
				if (!name || typeof name !== 'string') return colors[0];
				const firstChar = name.charAt(0).charCodeAt(0);
				return colors[firstChar % colors.length];
			},
			// 获取头像显示的文本（姓氏）
			getAvatarText(name) {
				if (!name || typeof name !== 'string') return '未';
				return name.charAt(0);
			},

			// 选择添加客人方式
			selectAddGuestMethod(method) {
				// 关闭弹窗
				this.showAddGuestModal = false;

				if (!this.currentOrder) return;

				// 准备订单参数
				const orderStr = encodeURIComponent(JSON.stringify(this.currentOrder));

				if (method === 'basic') {
					// 基础添加：跳转到编辑客人页面
					uni.navigateTo({
						url: `/pages/editGuest/editGuest?groupId=${this.groupId}&mode=add&order=${orderStr}`
					});
				} else if (method === 'smart') {
					// 智能解析：跳转到智能解析页面，使用相同的参数格式
					uni.navigateTo({
						url: `/pages/smartParse/smartParse?groupId=${this.groupId}&order=${orderStr}`
					});
				}
			}
		}
	};
</script>

<style scoped>
	@import './tourGroupDetail.css';

	.icon-unbind {
		color: #FF4D4F;
		font-size: 22rpx;
		cursor: pointer;
		padding: 4rpx;
		border-radius: 50%;
		background-color: rgba(255, 77, 79, 0.1);
	}

	.status-edit-icon {
		width: 20px;
		height: 20px;
		margin-left: -5px;
		vertical-align: middle;
		cursor: pointer;
	}
</style>